//
//  SelDeliveryDishViewController.m
//  OrderSeat
//
//  Created by 王威 on 13-12-6.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "SelDeliveryDishViewController.h"
#import "SelDeliveryDishListViewController.h"
#import "SelectDishLeftCell.h"
#import "SelectDishRightCell.h"

#define TOP_LOCATION CGRectMake(0, 0, 1, 1)

@implementation SelDeliveryDishViewController

- (id)initWithShopId:(NSString*)shopId
{
    self = [super initWithNibClass:[SelDeliveryDishViewController class]];
    if (self) {
        self.shopId = shopId;
        _photoList = [[NSMutableArray alloc] initWithCapacity:5];
        _selectedDishList = [[NSMutableArray alloc] initWithCapacity:10];
        _dataSource = [[SelDeliveryDishDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    
    [_dataSource fetchDishCategories];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [AppDelegate sharedInstance].tabBarController.tabbarView.hidden = YES;
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"外卖点菜"];
    
    _leftTable.dataSource = self.rightTable.dataSource = _dataSource;
    _leftTable.delegate = self.rightTable.delegate = _dataSource;
    
    _rightTable.height = ScreenHeight-NavBarHeight-StatusBarHeight- _footerView.height;
    _leftTable.height = _rightTable.height;
    
    _footerView.top = _rightTable.bottom;
    
    [_leftTable drawBorder];
}

- (void)leftButtonClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    [AppDelegate sharedInstance].tabBarController.tabbarView.hidden = NO;
}

- (void)selectSmallCatFinished:(NSInteger)catId
{
    for (NSMutableDictionary *dic in _dataSource.catList) {
        NSString *_catId = [dic objectForKey:@"lbid"];
        
        if ([_catId isEqualToString:INT_TO_STR(catId)]) {
            [dic setObject:@"1" forKey:@"selected"];
            continue;
        }
        
        [dic setObject:@"0" forKey:@"selected"];
    }
    
    [_leftTable reloadData];
    [_dataSource fetchDishWithCatId:INT_TO_STR(catId)];
}

- (void)selectDishCountFinished
{
    int totalCount = 0;
    float totalMoney = 0;
    
    [_selectedDishList removeAllObjects];
    
    //获取每个分类下的菜品选择数量，将已经选择了的加入_selectedDishList数组中
    for (NSString *catId in [_dataSource.dishCache allKeys]) {
        NSMutableArray *dishList = [_dataSource.dishCache objectForKey:catId];
        
        int catCount = 0;
        for (NSDictionary *dic in dishList) {
            int count = [[dic objectForKey:@"fenshu"] intValue];
            float money = [[dic objectForKey:@"price"] floatValue];
            
            catCount += count;
            totalCount += count;
            totalMoney += money*count;
            
            if (count > 0) [_selectedDishList addObject:dic];
        }
        
        for (NSMutableDictionary *dic in _dataSource.catList) {
            if ([[dic objectForKey:@"lbid"] isEqualToString:catId]) {
                [dic setObject:INT_TO_STR(catCount) forKey:@"fenshu"];
                break;
            }
        }
    }
    
    [self.leftTable reloadData];
    self.totalCountLabel.text = [NSString stringWithFormat:@"%d道菜/",totalCount];
    self.totalMoneyLabel.text = [NSString stringWithFormat:@"￥%.0f元",totalMoney];
}

- (void)tapImageWithIndex:(NSInteger)index
{
    [_photoList removeAllObjects];
    if (_photoList.count == 0) {
        for (NSDictionary *dic in _dataSource.dishList) {
            NSString *url = [dic objectForKey:@"image"];
            NSString *name = [dic objectForKey:@"name"];
            NSString *price = [NSString stringWithFormat:@"￥%@",[dic objectForKey:@"price"]];
            NSString *unit = [NSString stringWithFormat:@"/%@",[dic objectForKey:@"danwei"]];
            NSString *description = [NSString stringWithFormat:@"名称:%@  价格:%@%@",name,price,unit];
            
            MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
            photo.caption = description;
            [_photoList addObject:photo];
        }
    }
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;
    browser.displayNavArrows = YES;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = NO;
    browser.wantsFullScreenLayout = YES;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    [browser setCurrentPhotoIndex:index];
    
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:nc animated:YES];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photoList.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photoList.count)
        return [_photoList objectAtIndex:index];
    return nil;
}

- (IBAction)nextAction:(id)sender
{
    if (_selectedDishList.count == 0) {
        [AppDelegate showMessage:@"您忘记选择菜品了，请先选择菜品"];
        return;
    }
     
    SelDeliveryDishListViewController *selectedDishListVC = [[SelDeliveryDishListViewController alloc] init];
    selectedDishListVC.shopId = self.shopId;
    selectedDishListVC.tel = self.tel;
    selectedDishListVC.selectedDishList = self.selectedDishList;
    [self.navigationController pushViewController:selectedDishListVC animated:YES];
}

@end

//=================================================================================
#pragma==============数据源实现======================================================
//=================================================================================

@implementation SelDeliveryDishDataSource

#define DISH_CAT_TAG 1
#define DISH_LIST_TAG 2

#define DISH_CAT_TAB_TAG 11
#define DISH_LIST_TAB_TAG 12

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
        _dishList = [[NSMutableArray alloc] initWithCapacity:10];
        _dishCache = [[NSMutableDictionary alloc] initWithCapacity:10];
        _catList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    return self;
}

- (void)fetchDishCategories
{
    NSString *url = [NSString stringWithFormat:API_DSHOP_CAT, self.viewController.shopId];
    [self get:url tag:DISH_CAT_TAG];
}

- (void)fetchDishWithCatId:(NSString*)catId
{
    NSMutableArray *dish = [_dishCache objectForKey:catId];
    if (dish) {
        self.dishList = dish;
        [_viewController.rightTable reloadData];
        [_viewController.rightTable scrollRectToVisible:TOP_LOCATION animated:YES];
        return;
    }
    
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_DSHOP_DISH, self.viewController.shopId,catId];
    [self get:url tag:DISH_LIST_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@", request.responseString);
    
    NSDictionary *json = [request.responseData JSONValue];
    
    if (request.tag == DISH_CAT_TAG) {
        self.catList = [json objectForKey:@"data"];
        if (self.catList.count > 0) {
            for (NSMutableDictionary *dic in self.catList) {
                [dic setObject:@"0" forKey:@"selected"];
            }
            
            NSMutableDictionary *dic = [self.catList objectAtIndex:0];
            [dic setObject:@"1" forKey:@"selected"];
            
            NSString *catId = [dic objectForKey:@"lbid"];
            [self fetchDishWithCatId:catId];
        }
        
        [self.viewController.leftTable reloadData];
    }
    
    if (request.tag == DISH_LIST_TAG) {
        NSString *catId = [json objectForKey:@"lbid"];
        self.dishList = [json objectForKey:@"dish"];
        
        for (NSMutableDictionary *dic in self.dishList) {
            [dic setObject:@"0" forKey:@"fenshu"];
        }
        
        [_dishCache setObject:_dishList forKey:catId];
        
        [_viewController.rightTable reloadData];
        [_viewController.rightTable scrollRectToVisible:TOP_LOCATION animated:YES];
        
        [SVProgressHUD dismiss];
    }
}

#pragma ===================加载tableview数据 Begin================================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return tableView.tag == DISH_CAT_TAB_TAG ? 41 : 78;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tableView.tag == DISH_CAT_TAB_TAG ? _catList.count : _dishList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == DISH_CAT_TAB_TAG) {
        static NSString *CellIdentifier = @"SelectDishLeftCell";
        
        SelectDishLeftCell *cell = [_viewController createCellWithNib:CellIdentifier tableview:tableView];
        cell.delegate = self.viewController;
        [Functions disabledDelaysContentTouches:cell];
        
        NSDictionary *dic = [self.catList objectAtIndex:indexPath.row];
        [cell setContent:dic];
        
        return cell;
    }
    
    if (tableView.tag == DISH_LIST_TAB_TAG) {
        static NSString *CellIdentifier = @"SelectDishRightCell";
        
        SelectDishRightCell *cell = [_viewController createCellWithNib:CellIdentifier tableview:tableView];
        cell.delegate = self.viewController;
        [Functions disabledDelaysContentTouches:cell];
        
        NSMutableDictionary *dic = [self.dishList objectAtIndex:indexPath.row];
        [cell setContent:dic andIndex:indexPath.row];
        
        return cell;
    }
    
    return nil;
}

@end